﻿using BrnMall.Core;
using BrnMall.Manager.Domain.Ship;
using BrnMall.Manager.Manager.Ship;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Services
{
    public class ShipOrders
    {
        static object lockObj = new object();

        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="oid">订单id</param>
        /// <param name="orderState">订单状态</param>
        /// <param name="paySN">支付单号</param>
        /// <param name="payTime">支付时间</param>
        public static void PayOrder(int oid, OrderState orderState, string paySN, DateTime payTime)
        {
            int state = (int)orderState;
            var orderInfo = new ShipOrder();
            //是否重复
            lock (lockObj)
            {
                orderInfo = ShipOrderManager.Get(oid);
                if (orderInfo == null)
                    return;
                if (orderInfo.OrderState == ((int)OrderState.PreProducting))
                {
                    Trace.TraceError(string.Format("ShipOrders.cs 充值回调，同一单号不能重复充值，参数：订单ID：{0}，订单状态：{1}，支付单号：{2}，支付时间：{3}", oid, state, paySN, payTime));
                    return;
                }

                var cashInfo = ShipCashManager.GetInfo(orderInfo.StoreId);

                //新的余额
                decimal cash = DecodeCash(cashInfo.Cash) + orderInfo.OrderAmount + orderInfo.GiveAmount;

                //新的赠送总额
                decimal giveCash = cashInfo.GiveCash + orderInfo.GiveAmount;

                //更改订单状态
                int order_count = ShipOrderManager.PayOrder(oid, orderState, paySN, payTime);
                if (order_count < 1)
                {
                    Trace.TraceError(string.Format("ShipOrders.cs 充值回调，订单更新失败，参数：会员ID：{0}，订单ID：{1},订单状态：{2}，支付单号：{3}，支付时间：{4}", orderInfo.Uid, oid, orderState, paySN, payTime));
                    return;
                }

                //更新余额
                int cash_count = ShipCashManager.UpdateCash(orderInfo.StoreId, EncodeCash(cash));
                if (cash_count < 1)
                    Trace.TraceError(string.Format("ShipOrders.cs 充值回调，余额更新失败，参数：订单id:{5}, 会员ID：{0}，旧余额：{1}, 旧赠送总额：{2}, 订单金额：{3}, 订单赠送金额：{4}", orderInfo.Uid, cashInfo.Cash, cashInfo.GiveCash, orderInfo.OrderAmount, orderInfo.GiveAmount, oid));

                //添加充值记录
                var record = new ShipRecord() { Uid = orderInfo.Uid, StoreId = orderInfo.StoreId, Amount = orderInfo.OrderAmount, GiveAmount = orderInfo.GiveAmount, Balance = cash, Direction = 1, remark = "支付宝充值", CreateTime = DateTime.Now };
                ShipRecordManager.Add(record);
            }
        }

        /// <summary>
        /// 添加配送资金，并添加扣款记录
        /// </summary>
        public static string AddCash(int uid, int storeId, decimal Amount, string remark, string osn = "")
        {
            //获取余额
            var userCash = ShipCashManager.GetInfo(storeId);
            if (userCash == null)
            {
                Trace.TraceError(string.Format("ShipOrders.cs 未开通配送资金账户，方法：AddCash({0},{1},{2},{3})", uid, storeId, Amount, remark));
                return "未开通配送资金账户";
            }

            decimal cash = DecodeCash(userCash.Cash) + Amount;       //余额=旧余额+交易金额
            if (cash < 0) cash = 0;

            //更新余额
            int cash_count = ShipCashManager.UpdateCash(storeId, EncodeCash(cash));
            if (cash_count > 0)
            {
                //添加交易记录
                var record = new ShipRecord() { Uid = uid, StoreId = storeId, Amount = Amount, GiveAmount = 0, Balance = cash, Direction = 1, remark = remark, CreateTime = DateTime.Now, OSN = osn };
                ShipRecordManager.Add(record);
            }
            else
            {
                Trace.TraceError(string.Format("ShipOrders.cs 增加配送余额失败，方法：AddCash({0},{1},{2},{3})", uid, storeId, Amount, remark));
                return "配送余额增加失败";
            }
            return "";
        }


        /// <summary>
        /// 扣除配送资金，并添加扣款记录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="Amount">扣除的余额</param>
        /// <returns></returns>
        public static string ConsumeCash(int uid, int storeId, decimal Amount, string remark,string osn="")
        {
            //获取余额
            var userCash = ShipCashManager.GetInfo(storeId);
            if (userCash == null) return "未开通配送账户";
            if (DecodeCash(userCash.Cash) < Amount) return "配送余额不足";

            decimal cash = DecodeCash(userCash.Cash) - Amount;       //余额=旧余额-交易金额
            if (cash < 0) cash = 0;

            //更新余额
            int cash_count = ShipCashManager.UpdateCash(storeId, EncodeCash(cash));
            if (cash_count > 0)
            {
                //添加交易记录
                var record = new ShipRecord() { Uid = uid, StoreId = storeId, Amount = Amount * -1, GiveAmount = 0, Balance = cash, Direction = 2, OSN = osn, remark = remark, CreateTime = DateTime.Now };
                ShipRecordManager.Add(record);
            }
            else
            {
                Trace.TraceInformation(string.Format("ShipOrders.cs 扣除余额失败，方法：ConsumeCash({0},{1},{2},{3},{4})， 单笔金额:{2}", uid, storeId, Amount, remark, osn));
                return "配送余额扣除失败";
            }
            return "";
        }

        /// <summary>
        /// 添加系统账号交易记录
        /// </summary>
        /// <returns></returns>
        public static bool AddSysRecord(decimal amount, int direction, string remark, string osn = "")
        {
            var record = new ShipRecord() { Uid = 0, StoreId = 0, Amount = amount, GiveAmount = 0, Balance = 0, Direction = direction, OSN = osn, remark = remark, CreateTime = DateTime.Now };
            return ShipRecordManager.Add(record);
        }

        /// <summary>
        /// 加密余额
        /// </summary>
        /// <param name="cash"></param>
        /// <returns></returns>
        public static string EncodeCash(decimal cash)
        {
            return cash.ToString();
        }

        /// <summary>
        /// 解密余额
        /// </summary>
        /// <param name="cash"></param>
        /// <returns></returns>
        public static decimal DecodeCash(string cash)
        {
            return Convert.ToDecimal(cash);
        }

        /// <summary>
        /// 保存达达门店状态
        /// </summary>
        /// <param name="uid">店铺自己的uid</param>    
        /// <param name="storeId">店铺ID</param>
        /// <param name="shopState">达达门店状态(0 未开通, 1 已开通)</param>
        public static void AddOrUpdateShopState(int uid, int storeId, int shopState)
        {
            var cashModel = ShipCashManager.GetInfo(storeId);
            if (cashModel == null)
                ShipCashManager.Add(new ShipCash() { Uid = uid, StoreId = storeId, ShopState = shopState, Cash = "0", GiveCash=0, Cash_Decode = 0 });
            else
                ShipCashManager.UpdateShopState(storeId, shopState);  //更新状态
        }
    }
}
